

import React,{useState,useEffect} from 'react'
import {PlusOutlined,CloseCircleFilled} from '@ant-design/icons'
import { Upload,Button,Image,message } from 'antd'
import {requestHeader,transformResponse} from '@utils/request'
import {isFunction} from '@utils/base'
import './index.css'

export const beforeUpload=(file,size)=>{
  const isLt2M = file.size / 1024 / 1024 < size;
  if (!isLt2M) {
    message.error('上传图片不能大于'+size+'M！')
  }
  return isLt2M;
}

export default ({
  accept="image/*",
  text='上传图片',
  url='/admin/fileHander/upload',
  hideUpload=false,
  fileName='file',
  fileSize=5,
  imageList=[],
  uploadSuccess=()=>{},
  removeImage=()=>{},
  imageWidth=120,
  imageHeight=120,
  renderBottomBtn=()=>{}
})=>{
  // let [imgs,setImgs] = useState([...imageList])
  let [loading,setLoading] = useState(false)
  let [headers] = useState(()=>{
    if(isFunction(requestHeader)){
      return requestHeader()
    }
    return {}
  })
  // useEffect(()=>{
  //   setImgs([...imageList])
  // },[imageList])
  const shareChange = (file)=>{
    if(file.file&&file.file.response){

      let {errorCode,result} = isFunction(transformResponse)? transformResponse(file.file.response):file.file.response
      if(errorCode==0){
        uploadSuccess(result)
      }
      setLoading(false)
    }
  }
  return <>
    {hideUpload?null:<div className="admin-upload-control">
      <Upload
        accept={accept}
        name={fileName}
        action={url}
        headers={headers}
        withCredentials={true}
        beforeUpload={(e)=>{
          let bl = beforeUpload(e,fileSize)
          if(bl) setLoading(true)
          return bl
        }}
        onChange={shareChange}
      >
        <Button loading={loading}>
          <PlusOutlined />{text}
        </Button>
      </Upload> 
    </div>}
    {
      imageList.map((item,index)=>{
        let isVideo = item.indexOf('.mp4')>-1
        return <div key={index} className={'upload-image-main'}>
          <CloseCircleFilled onClick={()=>{
            removeImage(index)
          }} className={'upload-image-close'} />
          
          {isVideo? <video className="upload-admin-video" controls src={item}>
            </video>:  <Image preview={true} height={imageHeight} width={imageWidth} src={item} alt=""/>}
          {renderBottomBtn?renderBottomBtn(index):null}
        </div>
      })
    }
  </>
}

